﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.ExceptionServices;
using System.Threading;
using Microsoft.Practices.Unity;
using SpectrumAnalyser.Common.Logs;
using SpectrumAnalyser.Common.Logs.Attributes;


namespace SpectrumAnalyser.Shell
{
    [Log]
    public class Program : IWithLog
    {
        public static void Main()
        {
            var thread = new Thread(() =>
                                        {
                                            AppDomain.CurrentDomain.AssemblyResolve += OnResolveAssembly;
                                            var application = new App();
                                            application.InitializeComponent();
                                            application.Run();
                                        });
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
        }

        private static Assembly OnResolveAssembly(object sender, ResolveEventArgs args)
        {
            var executingAssembly = Assembly.GetExecutingAssembly();
            var assemblyName = new AssemblyName(args.Name);

            string path = assemblyName.Name + ".dll";
            if (assemblyName.CultureInfo.Equals(CultureInfo.InvariantCulture) == false)
            {
                path = String.Format(@"{0}\{1}", assemblyName.CultureInfo, path);
            }

            using (Stream stream = executingAssembly.GetManifestResourceStream(path))
            {
                if (stream == null)
                    return null;

                var assemblyRawBytes = new byte[stream.Length];
                stream.Read(assemblyRawBytes, 0, assemblyRawBytes.Length);
                return Assembly.Load(assemblyRawBytes);
            }
        }

        #region Implementation of IWithLog

        public Logger Logger { get; set; }

        #endregion
    }
}